package org.stephen.recommend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.stephen.recommend.enums.LanguageType;
import org.stephen.recommend.mapper.CmsArticleMapper;
import org.stephen.recommend.entity.Article;
import org.stephen.recommend.service.BaseService;
import org.stephen.recommend.service.CmsArticleService;
import org.stephen.recommend.util.CommonUtils;
import org.stephen.recommend.util.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * ClassName: CmsArticleService
 * Description:
 * Date: 2020/12/9 10:01
 *
 * @author stephen.qiu
 * @version 1.0
 */

@Service
public class CmsArticleServiceImpl extends BaseService<CmsArticleMapper, Article> implements CmsArticleService {
    @Autowired
    CmsArticleMapper cmsArticleMapper;

    private final static int ARTICLE_TAG_NUM =10;

    @Override
    public HashMap<String, Double> getTagMapByArticles(String[] articleIds, LanguageType languageType) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.select("id", "tag");
        queryWrapper.in("id", articleIds);
        queryWrapper.eq("article_type", 1);
        queryWrapper.eq("language", languageType.getCode());
        queryWrapper.eq("del_flag", 0);
        List<Article> articles = cmsArticleMapper.selectList(queryWrapper);
        HashMap<String, Double> map = new HashMap<>(CommonUtils.initHashMapSize(articles.size() * ARTICLE_TAG_NUM));
        articles.forEach(article -> {
            if (Utils.isNotEmpty(article.getTag()) && article.getTag().length() >= ARTICLE_TAG_NUM) {
                String[] tags = article.getTag().split(",");
                for (String tag : tags) {
                    Double d = map.getOrDefault(tag.split(":")[0], 0.0d) + Double.valueOf(tag.split(":")[1]);
                    map.put(tag.split(":")[0], d);
                }
            }
        });
        return map;
    }
}
